package stocks

import (
	"fmt"
	"html/template"

	"gitee.com/chenrh/finego/app"
	"gitee.com/chenrh/finego/backends/crawler"
	"gitee.com/chenrh/finego/backends/models"
	"gitee.com/chenrh/finego/backends/ui"
	"gitee.com/chenrh/finego/backends/utils"
	"gitee.com/chenrh/gotoolkit/conv"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	// "strings"
)

// StockListController serves the "/", "/ping" and "/hello".
type StockListController struct {
	// Optionally: context is auto-binded by Iris on each request,
	// remember that on each incoming request iris creates a new UserController each time,
	// so all fields are request-scoped by-default, only dependency injection is able to set
	// custom fields like the Service which is the same for all requests (static binding).
	Ctx iris.Context

	// Our UserService, it's an interface which
	// is binded from the main application.
	//Service services.UserService
}

// BeforeActivation 注册自定义的路由
func (c *StockListController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("POST", "/selfselect/add", "AddSelfSelectStock")
	b.Handle("POST", "/selfselect/remove", "RemoveSelfSelectStock")
}

// GetList  股票列表界面
func (c *StockListController) GetList() mvc.Result {
	var pageindex int64 = conv.ToInt64(c.Ctx.URLParam("page"), 1) - 1
	var pagesize int64 = 15
	var datacount int64 = 0

	keywords := c.Ctx.URLParam("keywords")
	kind := c.Ctx.URLParam("kind")
	if app.DB.HasInjectChar(keywords) {
		keywords = ""
	}
	if app.DB.HasInjectChar(kind) {
		kind = "sh"
	}
	if len(kind) == 0 {
		kind = "all"
	}

	datasql := fmt.Sprintf("select * from stock_info a where (a.company_code like '%%%s%%' or a.company_abbr like '%%%s%%')", keywords, keywords)
	if kind == "sh" || kind == "sz" {
		datasql += fmt.Sprintf(" and a.company_kind = '%s'", kind)
	} else if kind == "self" {
		islogin, userCache := utils.UserCache(c.Ctx)
		if islogin == false {

		}
		datasql += fmt.Sprintf(" AND EXISTS (SELECT 1 FROM stk_self_select b WHERE b.company_code = a.company_code AND b.user_id = '%d')", userCache.UserID)
	}

	cuntsql := fmt.Sprintf("select count(*) cnt from (%s) t", datasql)

	arr, _ := app.DB.Select(datasql+" order by a.company_code asc limit ?,?", pageindex*pagesize, pagesize)
	cnt, _ := app.DB.Select(cuntsql)

	if len(cnt) > 0 {
		datacount = cnt[0]["cnt"].(int64)
	}

	fmt.Println(datasql)

	pagecontrol := ui.NewPagination(c.Ctx.Request(), datacount, pagesize)
	htmlpages := pagecontrol.Pages()

	return mvc.View{
		Name: "stocks/stocks.list.html",
		Data: iris.Map{
			"Title":       "股票数据列表",
			"StockRows":   arr,
			"Keywrods":    keywords,
			"SearchKind":  kind,
			"PageControl": template.HTML(htmlpages),
		},
	}
}

// PostCrawler 抓取
func (c *StockListController) PostCrawler() {
	// 清空原有数据
	app.GetDB().Exec("TRUNCATE TABLE stock_info")

	sse := crawler.Sse{}
	sse.CrawlerStocks()

	szse := crawler.Szse{}
	szse.CrawlerStocks()

	c.Ctx.JSON(iris.Map{"flag": true, "msg": ""})
	return
}

// AddSelfSelectStock 加入自选
func (c *StockListController) AddSelfSelectStock() {
	code := c.Ctx.FormValue("code")
	islogin, userCache := utils.UserCache(c.Ctx)

	if islogin == false {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "请先登录"})
		return
	}

	modelSel := models.STK_SELF_SELECT{
		COMPANY_CODE: code,
		USER_ID:      userCache.UserID,
	}

	app.GetDB().Create(&modelSel)

	c.Ctx.JSON(iris.Map{"flag": true, "msg": ""})
	return
}

// RemoveSelfSelectStock  删除自选
func (c *StockListController) RemoveSelfSelectStock() {
	code := c.Ctx.FormValue("code")
	islogin, userCache := utils.UserCache(c.Ctx)

	if islogin == false {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "请先登录"})
		return
	}

	app.GetDB().Delete(models.STK_SELF_SELECT{}, "user_id = ? and company_code = ?", userCache.UserID, code)
	c.Ctx.JSON(iris.Map{"flag": true, "msg": ""})
	return
}
